<script lang="ts" setup>
import { ref, reactive, defineAsyncComponent, computed } from 'vue'
import { queryStoreOrderDetailInfo } from '@/api/order'
import { queryStoreOrderDetailInfoResponseData } from '@/api/order/types/order'
// import CustomFormItem from '@/components/basic/CustomFormItem.vue'
import { getToken } from '@/utils/cache/cookies'
import { ElMessage, FormInstance, FormRules } from 'element-plus'
import { changeOrderDetailInfo } from '@/api/order'
const TimeInput = defineAsyncComponent(() => import('@/components/basic/ui-elements/TimeInput.vue'))
const dialogVisible = ref<boolean>(false)
const orderId = ref<string>('')
const previousOrderId = ref<string | null>(null)
const open = async () => {
  if (orderId.value !== previousOrderId.value) {
    previousOrderId.value = orderId.value
    await getAdjustInfo()
  }
  dialogVisible.value = true
}
const setId = (newId: string) => {
  orderId.value = newId
}
defineExpose({ open, setId })

const data = ref<queryStoreOrderDetailInfoResponseData | null>(null)
const getAdjustInfo = async () => {
  try {
    const res = await queryStoreOrderDetailInfo({
      token: getToken() ?? '',
      orderId: orderId.value
    })
    if (res.statusCode === '0') {
      data.value = res.data
    }
  } catch (error) {
    console.error(error)
  }
}
const form = reactive({
  type: '0',
  reason: '',
  days: 0,
  hours: 0,
  minutes: 0,
  times: 0,
  overdueDays: 0
})
const formRef = ref<FormInstance | null>(null)
const rules = reactive<FormRules>({
  type: [
    {
      required: true,
      message: '请选择操作类型',
      trigger: 'change'
    }
  ],
  reason: [
    {
      required: true,
      message: '请输入套餐调整原因',
      trigger: 'blur'
    }
  ]
})
// 解析 remainTime 字段
const parseRemainingTime = (remainingTime?: string) => {
  const timeValues = { days: 0, hours: 0, minutes: 0, times: 0 }
  if (!remainingTime) return timeValues
  if (data.value?.isLongTerm === 0) {
    const dayMatch = remainingTime.match(/(\d+)\s*天/)
    const hourMatch = remainingTime.match(/(\d+)\s*(小时|时)/)
    const minuteMatch = remainingTime.match(/(\d+)\s*(分钟|分)/)

    timeValues.days = dayMatch ? parseInt(dayMatch[1], 10) : 0
    timeValues.hours = hourMatch ? parseInt(hourMatch[1], 10) : 0
    timeValues.minutes = minuteMatch ? parseInt(minuteMatch[1], 10) : 0
  } else {
    const timesMatch = remainingTime.match(/(\d+)\s*次/)
    timeValues.times = timesMatch ? parseInt(timesMatch[1], 10) : 0
  }

  return timeValues
}
const parseUnpaidTime = (unpaidTime?: string) => {
  if (!unpaidTime) return 0
  const dayMatch = unpaidTime.match(/(\d+)\s*天/)
  return dayMatch ? parseInt(dayMatch[1], 10) : 0
}

const maxOverdueDays = computed(() => parseUnpaidTime(data.value?.unpaidTime))
const timeValues = computed(() => parseRemainingTime(data.value?.remainTime))
// 计算最大值限制
const maxValues = computed(() => {
  if (form.type === '1') {
    return {
      days: timeValues.value.days,
      hours: timeValues.value.hours,
      minutes: timeValues.value.minutes,
      times: timeValues.value.times
    }
  }
  return {
    days: Infinity,
    hours: 23,
    minutes: 59,
    times: Infinity
  }
})
const handleTypeChange = () => {
  if (form.type === '0') {
    form.days = 0
    form.hours = 0
    form.minutes = 0
    form.times = 0
  } else if (form.type === '1') {
    form.days = maxValues.value.days
    form.hours = maxValues.value.hours
    form.minutes = maxValues.value.minutes
    form.times = maxValues.value.times
  }
}
const cancle = () => {
  dialogVisible.value = false
}
const loading = ref<boolean>(false)
const emits = defineEmits(['refresh'])
const confirm = () => {
  loading.value = true
  formRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        const res = await changeOrderDetailInfo({
          token: getToken() ?? '',
          orderId: orderId.value,
          type: form.type,
          day: form.type === '2' ? form.overdueDays : form.days,
          hour: form.hours,
          minute: form.minutes,
          times: form.times,
          reason: form.reason
        })
        if (res.statusCode === '0') {
          ElMessage.success(res.data)
          dialogVisible.value = false
          emits('refresh')
        }
        loading.value = false
      } catch (error) {
        console.error(error)
        loading.value = false
      }
    } else loading.value = false
  })
}
const handleClose = () => {
  formRef.value?.resetFields()
  form.days = 0
  form.hours = 0
  form.minutes = 0
  form.times = 0
  form.overdueDays = 0
}
</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    title="套餐信息调整"
    width="650px"
    class="adjust-term-dialog"
    @close="handleClose"
  >
    <el-form :model="form" ref="formRef" :rules="rules" label-width="120px">
      <el-descriptions title="用户信息" :column="2">
        <el-descriptions-item label="用户手机号:">
          <span>{{ data?.userPhone }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="套餐类型:">
          <span>{{ data?.productType }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="订单:">
          <span>{{ data?.orderId }}</span> <span mt-10>({{ data?.productModel }})</span>
        </el-descriptions-item>
      </el-descriptions>
      <el-descriptions title="订单信息" :column="2">
        <el-descriptions-item label="租赁天/次数:">
          <span>{{ data?.rentTime }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="订单总逾期天数:">
          <span>{{ data?.overDueTime }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="未支付逾期天数:">
          <span>{{ data?.unpaidTime }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="剩余时长/次数:">
          <span
            >{{ data?.remainTime
            }}<span v-if="data?.giftTime"
              >(含赠送<span>{{ data?.isLongTerm === 0 ? '时长' : '次数' }}</span
              >{{ data.giftTime }})</span
            ></span
          >
        </el-descriptions-item>
      </el-descriptions>
      <el-descriptions title="调整订单" :column="1">
        <el-descriptions-item>
          <el-form-item prop="type" label="操作类型:">
            <el-radio-group v-model="form.type" @change="handleTypeChange">
              <el-radio value="0">增加时长/次数</el-radio>
              <el-radio value="1">扣除时长/次数</el-radio>
              <el-radio value="2" v-if="data?.overdue === 0">减少逾期天数</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-descriptions-item>
        <el-descriptions-item>
          <el-form-item v-if="form.type !== '2'" label="天/次数:">
            <time-input
              :is-long-term="data?.isLongTerm === 0"
              v-model="form"
              v-model:maxValues="maxValues"
            />
            <div class="text-[10px] text-grey leading-normal mt-5" v-show="form.type === '0'">
              <span>在此处添加的天/次数退款时不计入套餐统计，为赠送信息</span>
              <span class="text-warning-light">不计入套餐统计，为赠送信息</span>
            </div>
            <div class="text-[10px] text-grey leading-normal mt-5" v-show="form.type === '1'">
              <div>扣除套餐时长/次数时，如有赠送时长/次数优先扣除赠送时长/次数，</div>
              <div>如扣除的时长/次数＞赠送时长/次数，则会扣除原订单时长/次数，请谨慎操作！</div>
            </div>
          </el-form-item>
          <el-form-item v-if="form.type === '2'" label="天数:" prop="overdueDays">
            <el-input
              v-model="form.overdueDays"
              type="number"
              :min="0"
              :max="maxOverdueDays"
              placeholder="请输入天数"
            />
            <div class="text-[10px] text-grey leading-normal mt-5">
              <div>该功能只支持对未支付的逾期天数进行调整，调整后用户支付剩余天数即可，</div>
              <div>已支付的需要减少天数请提交退款申请</div>
            </div>
          </el-form-item>
        </el-descriptions-item>
        <el-descriptions-item>
          <el-form-item prop="reason" label="调整原因:">
            <el-input v-model="form.reason" type="textarea" :min="2" placeholder="请输入调整原因" />
          </el-form-item>
        </el-descriptions-item>
      </el-descriptions>
    </el-form>
    <template #footer>
      <el-button plain @click="cancle">取消</el-button>
      <el-button type="primary" @click="confirm" :loading="loading">确定</el-button>
    </template>
  </el-dialog>
</template>

<style scoped></style>
